/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package beans;

import entities.Spot;
import entities.User;
import java.util.List;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Ahmet
 */
@ManagedBean
@SessionScoped
public class UserBean {
    @PersistenceContext 
    private EntityManager em;

    private User user;
    public String username;
    
    public UserBean() {
    }

    public User getUser() {
        FacesContext context = FacesContext.getCurrentInstance();
        Map<String,String> params = context.getExternalContext().getRequestParameterMap();
        username = params.get("username");
        user = (User) em.find(User.class, username);
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
        //this.user = (User) em.find(User.class, username);
    }

//    public void attrListener(ActionEvent event) {
//        username = (String) event.getComponent().getAttributes().get("username");
//    }
//
//    public String outcome() {
//        FacesContext context = FacesContext.getCurrentInstance();
//        Map<String,String> params = context.getExternalContext().getRequestParameterMap();
//        username = params.get("username");
//        return "viewuser";
//    }

    public List<Spot> listSpots() {
        try {
            return (List<Spot>) em.createNamedQuery("Spot.findByUsername").setParameter("username", user).getResultList();
        } catch (NoResultException nre) {
            return null;
        }
    }
}
